import VNode from '../vnode/index.js'
import { getTemplateToVnode, getVnodeByTemplate, prepareRender } from './render.js';
 
/**
 * 给MiniVue添加挂载方法
 * @param {*} 根元素 
 */
export function initMount(MiniVue) {
    MiniVue.prototype.$mount = function (el) {
        let root = document.getElementById(el);
        mount(this, root);
    }
}
 
/**
 * 实现mount事件
 * @param {*} vm 
 * @param {*} el 
 */
function mount(vm, el) {
    console.log('开始挂载')
    // 构建虚拟Dom
    vm._vnode = constructVnode(vm, el, parent);
    // 依赖收集
	prepareRender(vm,vm._node);
	console.log(getTemplateToVnode());
	console.log(getVnodeByTemplate());
}
 
export function constructVnode(vm, el, parent) {
    let vnode = null;
    const tag = el.nodeName
    const text = el.textContent.trim()
    const data = {}
    const nodeType = el.nodeType
    const key = ""
    vnode = new VNode(tag, el, [], text, data, parent, nodeType, key)
    // 递归构建子节点
    vnode.ele.childNodes.forEach(child => {
        const childNodes = constructVnode(vm, child, vnode)
        if(childNodes instanceof Array) {
            vnode.children.push(...childNodes)
        } else {
            vnode.children.push(childNodes)
        }
    })
    return vnode
}
 
/**
 * 获取节点的文本数据（文本节点）
 * @param {*} el 
 */
function getNodeText(el) {
    return el.nodeType === 3 ? el.textContent.trim() : ''
}
 